<?php

use Illuminate\Support\Facades\Mail;
use App\Admin\Eloquent\GiftActivity;
use App\Extensions\Upload\FileUpload;
use Symfony\Component\HttpFoundation\File\UploadedFile;

if (!function_exists('admin_action')) {
    /**
     * 根据 Admin 模块控制器 action 生成 url 链接
     *
     * @param  string $name
     * @param  array $parameters
     * @param  bool $absolute
     * @return string
     */
    function admin_action($name, $parameters = [], $absolute = true)
    {
        $namespace = '\App\Admin\Http\Controllers';

        return action($namespace . '\\' . $name, $parameters, $absolute);
    }
}

if (!function_exists('size2mb')) {
    /**
     * 转换数字为文件长度格式
     *
     * @param numeric $size
     * @param int $digits
     * @return string
     */
    function size2mb($size, $digits = 2)
    {
        //单位数组，是必须1024进制依次
        $unit = array('', 'K', 'M', 'G', 'T', 'P');

        //对数的基数
        $base = 1024;

        //字节数对1024取对数，值向下取整。
        $i = floor(log($size, $base));

        return round($size / pow($base, $i), $digits) . ' ' . $unit[$i] . 'B';
    }
}

if (!function_exists('upload_file')) {
    /**
     * 上传文件
     *
     * @param  \Symfony\Component\HttpFoundation\File\UploadedFile $uploadedFile
     * @param  array $config 上传文件配置
     * @return \App\Extensions\Upload\UploadFile|array  返回结果, code: 10000 成功, 10001 失败
     */
    function upload_file(UploadedFile $uploadedFile = null, $config = [])
    {
        if (!$uploadedFile) {
            return app('upload.file');
        }

        if (!empty($config)) {
            FileUpload::configure($config);
        }

        if ($json = FileUpload::handle($uploadedFile)) {
            return [
                'code' => 10000,
                'file' => [
                    'filename' => $json['originalName'],
                    'full_url' => $json['savepath'] . '/' . $json['savename'],
                ],
                'message' => '文件上传成功!'
            ];
        } else {
            return [
                'code' => 10001,
                'message' => FileUpload::getErrorMessage(),
            ];
        }
    }
}

if (!function_exists('asset')) {
    /**
     * 生成静态资源文件地址
     *
     * @param  string $path
     * @param  int $width 图片宽度
     * @param  int $height 图片高度
     * @return string
     */
    function asset($path, $width = null, $height = null)
    {
        return app('url')->asset($path);
    }
}
if (!function_exists('sendEmail')) {
    /**
     * 向指定的邮箱地址发送邮件
     */
    //发送邮件
    function sendEmail($data){
        //发送邮件
        Mail::send('emails.email', ['content'=>$data['content']], function($message)use($data){
            $message->to($data['email'])->subject($data['title']);
        });
        return true;
    }
}

if (!function_exists('create_code')) {
    /*
     * 随机生成一个不重复的$length位邀请码
     * $length
     */
    function create_code($length)
    {
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $max = strlen($strPol) - 1;

        for ($i = 0; $i < $length; $i++) {
            $str .= $strPol[rand(0, $max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }

        return $str;
    }
}
if (!function_exists('phone_code')) {
    /**
     * 生成手机验证码,并发送短信
     * string $num 手机号码
     * to_message  短信内容
     */
    function phone_code($num,$to_message)
    {
            //发送短信
            $clapi = new App\Extensions\SmsApi\SmsApi();
            $result = $clapi->sendSMS($num, $to_message, 'true');
            $result = $clapi->execResult($result);
            if (isset($result[1])&&$result[1] == 0) {
                //发送成功
                return true;
            } else {
                //发送失败
                return false;
            }
    }
}
if(!function_exists('createSn')){
    /**
     * 创建项目流水号
     */
    function createSn(){
        return date('YmdHis').rand(100000,999999);
    }
}

if (!function_exists('createSinaIdentityId')) {
    /**
     * 生成 sina identity_id
     *
     * @return string
     */
    function createSinaIdentityId()
    {
        return 'ibbl'.create_code(6);
    }
}

if(!function_exists('microtme_format')){

    /**
     * 格式化时间戳,精确到毫秒,x代表毫秒
     *
     * @param $format
     * @return mixed
     */
    function microtme_format($format)
    {
        list($usec, $sec) = explode(" ", microtime());
        $datetime = ((float)$usec + (float)$sec);

        list($usec, $sec) = explode(".", $datetime);
        $date = date($format, $usec);
        return str_replace('x', $sec, $date);
    }
}

if(!function_exists('login_added')){
    /**
     * 登录时，调用的附加操作
     * @return [type] [description]
     */
    function login_added()
    {
        GiftActivity::birthGift();//发送生日红包
    }
}
if(!function_exists('str_hide')){

    function str_hide($name){
        $lastname = mb_substr($name ,0, 1, 'utf-8');
        $firstname = mb_substr($name, 1, 10, 'utf-8');
        $length=mb_strlen($firstname,'utf-8');
        $str = null;
        for ($i = 0; $i < $length; $i++) {
            $str .='*';
        }
        return $lastname.$str;
    }
}

if (!function_exists('export_excel')) {
    function export_excel($name, $data = []){
        ob_clean();

        $newName = date('Y-m-d') . '-' . $name;

        Excel::create($newName, function($excel) use ($data){
            $excel->sheet('sheet', function($sheet) use ($data){
               $sheet->fromArray($data);
            });
        })->export('xls');
    }
}

if (!function_exists('qeury_export_excel')) {
    function qeury_export_excel($name, $data = []){
       $p_array  = [];
        if(is_object($data))
        $data = $data->toArray();
        for ($i=0; $i < count($data) ; $i++) { 
            if($i == 0){
                foreach ($data[$i] as $key => $value) {
                    $p_array[$i][$key] = $key; 
                    $p_array[$i+1][$key] = $value; 
                }
            }else{
                foreach ($data[$i] as $key => $value) {
                    $p_array[$i+1][$key] = $value; 
                }
            }
        }
            export_excel($name,$p_array);
    }
}